// config/game.js

const connection = require('./mysql.js');  // 应该是 mysql2/promise 创建的 pool
const redis = require('./redis.js');       // 假设 redis 客户端也正确导出

// 导入json文件
const level = require('./level.json');// 导入等级经验配置

/**
 * 所有地图 ID 列表
 * @type {string[]}
 */
let MAPS = [];


/**
 * 初始化地图配置：从 MySQL 加载地图和传送点，并写入 Redis
 */
async function initMapConfig() {
    // 把level配置整体写入redis
    await redis.set('level', JSON.stringify(level));
    try {
        const [results] = await connection.query(`
            SELECT 
                m.*,
                CAST(
                    JSON_ARRAYAGG(
                        IF(
                            e.entrance_id IS NOT NULL,
                            JSON_OBJECT(
                                'entrance_id', e.entrance_id,
                                'x', e.x,
                                'y', e.y,
                                'target_map_id', e.target_map_id,
                                'target_x', e.target_x,
                                'target_y', e.target_y,
                                'type', e.type
                            ),
                            NULL
                        )
                    ) AS CHAR
                ) AS entrances
            FROM maps m
            LEFT JOIN entrances e ON m.map_id = e.map_id
            GROUP BY m.map_id
        `);

        for (const row of results) {
            const mapId = row.map_id;
            MAPS.push(mapId);

            // ✅ 安全解析 entrances
            let entrances;
            if (row.entrances == null) {
                entrances = [];
            } else if (typeof row.entrances === 'string') {
                try {
                    entrances = JSON.parse(row.entrances);
                } catch (e) {
                    console.error(`JSON 解析失败 (${mapId}):`, row.entrances);
                    entrances = [];
                }
            } else if (Array.isArray(row.entrances)) {
                entrances = row.entrances.filter(item => item !== null);
            } else {
                console.warn(`未知 entrances 类型 (${mapId}):`, typeof row.entrances, row.entrances);
                entrances = [];
            }

            const mapData = {
                map_id: row.map_id,
                name: row.name,
                description: row.description,
                width: row.width,
                height: row.height,
                bg_image: row.bg_image,
                music: row.music,
                created_at: row.created_at,
                updated_at: row.updated_at,
                entrances: entrances,
            };

            try {
                await redis.set(mapId, JSON.stringify(mapData));
                console.log(`🔍 地图: ${mapId} || 加载完成 || 有${entrances.length}个传送点\r`);
            } catch (err) {
                console.error(`写入 Redis 失败 (${mapId}):`, err);
            }
        }

        console.log(`🎉 成功初始化 ${MAPS.length} 个地图及其传送点`);
    } catch (err) {
        console.error('初始化地图配置失败:', err);
    }
}

/**
 * 获取指定地图的完整配置（含传送点）
 * @param {string} mapId - 地图 ID
 * @returns {Object|null} 地图数据 + 传送门列表
 * {
 *   "map_id": "00000001",
 *   "name": "新手村",
 *   "width": 1000,
 *   "height": 800,
 *   "bg_image": "",
 *   "entrances": [
 *     {
 *       "entrance_id": "1",
 *       "x": 50,
 *       "y": 100,
 *       "target_map_id": "00000002",
 *       "target_x": 200,
 *       "target_y": 300,
 *       "type": 0
 *     }
 *   ]
 * }
 */
async function getMapConfig(mapId) {
    try {
        const data = await redis.get(mapId);
        return data ? JSON.parse(data) : null;
    } catch (err) {
        console.error('Redis 获取失败:', err);
        return null;
    }
}


module.exports = {
    MAPS,           // 注意：MAPS 可能初始化未完成时为空，见下方说明
    getMapConfig,
    initMapConfig, //
};